import math

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from Task.TaskProcessor import init_task
from Util.Return import get_image
from Util.SQL import *
from Data.DataAPI.Internet.API import *


@csrf_exempt
def tackle(request, scene_id, date, taskname):
    if request.method == "POST":
        task_id = init_task(taskname, [scene_id])   # 开始一个任务
        return JsonResponse({'task_id': task_id})
    ori_string = "SELECT bbox FROM data WHERE scene_id = '@';"
    sql_string = ori_string.replace("@", scene_id)
    bbox = select(sql_string)
    bbox1 = bbox[0]["bbox"]
    values = bbox1.strip('()').split(', ')
    for i in range(len(values)):
        values[i] = float(values[i])        # 最终处理得到的bbox值
    ori_string = "SELECT task_id,model_id as model_name,date,state FROM task WHERE scene_id = '@'"  # 查找这个地区现在所有任务的数据
    sql_string = ori_string.replace("@", scene_id)
    result = select(sql_string)
    for item in result:
        if 'date' in item:
            item['date'] = str(item['date'])    # 将时间转化为字符串形式
    result = result[::-1]
    img = get_image('quick_look', scene_id)    # 获取该地点quick_look图片
    if img is None:
        img = 1
    task = select("SELECT model_id,name as model_name,attribute as model_describe FROM model")     # 获取所有模型数据
    context = {"task": task, "img": img, "result": result, "nid": scene_id, "bbox": values, "date": date}
    return render(request, 'tackle.html', context)


@csrf_exempt
def tackle0(request):
    task_id = request.POST.get('task_id')
    img = get_image('available', task_id)
    if img is None:
        img = 1
    return JsonResponse({'img': img})


@csrf_exempt
def tackle1(request, scene_id, lng, lat, date):
    print(scene_id, lng, lat, date)
    dates = date.split('-')
    internet = InternetAPI()
    bbox = [float(lat), float(lng), float(lat), float(lng)]
    data = internet.get_data(bbox, [datetime(int(dates[0]), int(dates[1]), int(dates[2])), datetime(int(dates[0]), int(dates[1]), int(dates[2]))])
    print(data)
    for key in data:
        if key == "weather":
            for key1 in data[key]:
                for key2 in data[key][key1]:
                    if isinstance(data[key][key1][key2], float):
                        if math.isnan(data[key][key1][key2]):
                            data[key][key1][key2] = -300
    return JsonResponse({'data': data})
